<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./index.css">
</head>

<body>
    <div class="box" style="background-color: pink;">
        <div class="smallBox">
            <div class="mask"></div>
            <img src="./img/cw1.png" alt="">
        </div>

        <div class="bigBox">
            <img src="./img/cw1.png" alt="">
        </div>
    </div>

    <script>
        let mask = document.querySelector(".mask");
        let box = document.querySelector(".box");
        let smallBox = document.querySelector(".smallBox");
        let bigBox = document.querySelector(".bigBox");
        let bigBoxImg = bigBox.querySelector("img");
        let smallBoxImg = smallBox.querySelector("img");

        // // box.style.position = "relative";

        //遮罩层是在smallbox里面移动的，所以给smallbox事件监听
        smallBox.addEventListener("mouseover",function(e){
            mask.style.display = "block";
            bigBox.style.display = "block";

            //设置mask的x轴和y轴，实时获取鼠标的位置
            let x = e.pageX - box.offsetLeft - mask.offsetWidth/2;
            //e.pageX是距离小盒子左上角的距离 box.offsetLeft表示box这个盒子距离左边的偏移量 mask.offsetWidth/2是mask这个盒子的宽度的一半
            let y = e.pageY - box.offsetTop - mask.offsetHeight/2;

            //设置mask左右的最大移动距离
            let maxX = smallBox.offsetWidth - mask.offsetWidth;
            //smallBox自身的宽度 - mask自身的宽度
            let maxY = smallBox.offsetHeight - mask.offsetHeight;

            // 临界点
            (x <= 0) && (x = 0);
            (y <= 0) && (y = 0);
            (x >= maxX) && (x = maxX);
            (y >= maxY) && (y = maxY);

            //给mask设置transform属性，让它跟着鼠标移动
            mask.style.transform = `translate(${x}px,${y}px)`;
            
            // 移动大图片
            let bigImgX,
                bigImgY;

            // 公式:
            // 遮罩层最大移动距离 / 遮罩层当前移动距离
            // = 
            // 大图片最大移动距离 / 大图片当前移动距离(????)

            // 大图片当前移动距离 = 大图片最大移动距离 * 遮罩层当前移动距离 / 遮罩层最大移动距离;

            bigImgX = (bigBoxImg.offsetWidth - bigBox.offsetWidth) * x / maxX;
            bigImgY = (bigBoxImg.offsetHeight - bigBox.offsetHeight) * y / maxY;
            bigBoxImg.style.transform = `translate(${-bigImgX}px, ${-bigImgY}px)`;
        })

        smallBox.addEventListener("mouseout",function(){
            mask.style.display = "none";
            bigBox.style.display = "none";
        })


    </script>
</body>

</html>